import 'package:flutter/material.dart';
import '../models/program.dart';
import '../models/program_block.dart';
import 'program_block_widget.dart';

/// 程序编辑区域组件
class ProgramEditor extends StatefulWidget {
  final Program program;
  final Function(Program) onProgramChanged;
  
  const ProgramEditor({
    super.key,
    required this.program,
    required this.onProgramChanged,
  });

  @override
  State<ProgramEditor> createState() => _ProgramEditorState();
}

class _ProgramEditorState extends State<ProgramEditor> {
  // 当前选中的块
  ProgramBlock? _selectedBlock;
  
  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        color: Colors.grey.shade100,
        borderRadius: BorderRadius.circular(8.0),
        border: Border.all(color: Colors.grey.shade300),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 编辑区域标题
          Container(
            padding: const EdgeInsets.all(12.0),
            decoration: BoxDecoration(
              color: Colors.grey.shade200,
              borderRadius: const BorderRadius.only(
                topLeft: Radius.circular(8.0),
                topRight: Radius.circular(8.0),
              ),
            ),
            child: Row(
              children: [
                const Icon(Icons.code, color: Colors.blue),
                const SizedBox(width: 8.0),
                Expanded(
                  child: Text(
                    '程序编辑区域',
                    style: Theme.of(context).textTheme.titleMedium,
                    overflow: TextOverflow.ellipsis,
                  ),
                ),
                IconButton(
                  icon: const Icon(Icons.save),
                  tooltip: '保存程序',
                  onPressed: _saveProgram,
                  iconSize: 20,
                  padding: EdgeInsets.zero,
                  constraints: const BoxConstraints(),
                ),
                const SizedBox(width: 4),
                IconButton(
                  icon: const Icon(Icons.folder_open),
                  tooltip: '加载程序',
                  onPressed: _loadProgram,
                  iconSize: 20,
                  padding: EdgeInsets.zero,
                  constraints: const BoxConstraints(),
                ),
                const SizedBox(width: 4),
                IconButton(
                  icon: const Icon(Icons.delete),
                  tooltip: '清空程序',
                  onPressed: _clearProgram,
                  iconSize: 20,
                  padding: EdgeInsets.zero,
                  constraints: const BoxConstraints(),
                ),
              ],
            ),
          ),
          
          // 程序块放置区域
          Expanded(
            child: DragTarget<ProgramBlock>(
              onAccept: (block) {
                setState(() {
                  if (block.type == BlockType.event) {
                    widget.program.addStartBlock(block);
                    widget.onProgramChanged(widget.program);
                  }
                });
              },
              builder: (context, candidateData, rejectedData) {
                return SingleChildScrollView(
                  padding: const EdgeInsets.all(16.0),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      // 如果没有程序块，显示提示
                      if (widget.program.startBlocks.isEmpty)
                        const Center(
                          child: Padding(
                            padding: EdgeInsets.all(32.0),
                            child: Text(
                              '将程序块拖放到这里开始编程',
                              style: TextStyle(
                                color: Colors.grey,
                                fontSize: 16.0,
                              ),
                            ),
                          ),
                        ),
                      
                      // 显示所有起始块及其连接的块
                      for (var startBlock in widget.program.startBlocks)
                        _buildBlockChain(startBlock),
                    ],
                  ),
                );
              },
            ),
          ),
        ],
      ),
    );
  }
  
  // 构建块链（一个起始块及其所有连接的块）
  Widget _buildBlockChain(ProgramBlock block) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // 当前块
        Padding(
          padding: const EdgeInsets.symmetric(vertical: 4.0),
          child: Row(
            children: [
              Expanded(
                child: ProgramBlockWidget(
                  block: block,
                  isDraggable: false,
                  onTap: (block) {
                    setState(() {
                      _selectedBlock = block;
                    });
                    _showBlockOptionsDialog(block);
                  },
                ),
              ),
              IconButton(
                icon: const Icon(Icons.delete, color: Colors.red),
                onPressed: () {
                  setState(() {
                    widget.program.removeStartBlock(block);
                    widget.onProgramChanged(widget.program);
                  });
                },
                iconSize: 20,
                padding: EdgeInsets.zero,
                constraints: const BoxConstraints(),
                tooltip: '删除此块',
              ),
            ],
          ),
        ),
        
        // 子块（用于控制类块）
        if (block.children.isNotEmpty)
          Padding(
            padding: const EdgeInsets.only(left: 32.0),
            child: Container(
              decoration: BoxDecoration(
                border: Border(
                  left: BorderSide(
                    color: block.color.withOpacity(0.5),
                    width: 2.0,
                  ),
                ),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: block.children.map(_buildBlockChain).toList(),
              ),
            ),
          ),
        
        // 下一个块
        if (block.next != null)
          Padding(
            padding: const EdgeInsets.only(left: 16.0),
            child: Stack(
              children: [
                Positioned(
                  left: 0,
                  top: 0,
                  bottom: 0,
                  child: Container(
                    width: 2,
                    color: block.color.withOpacity(0.3),
                  ),
                ),
                _buildBlockChain(block.next!),
              ],
            ),
          ),
        
        // 如果没有下一个块，显示放置区域
        if (block.next == null)
          _buildDropTarget(block),
      ],
    );
  }
  
  // 构建块的放置区域
  Widget _buildDropTarget(ProgramBlock parentBlock) {
    return DragTarget<ProgramBlock>(
      onAccept: (block) {
        setState(() {
          if (block.type != BlockType.event) {
            parentBlock.next = block;
            widget.onProgramChanged(widget.program);
          }
        });
      },
      onWillAccept: (block) => block != null && block.type != BlockType.event,
      builder: (context, candidateData, rejectedData) {
        final isActive = candidateData.isNotEmpty;
        return AnimatedContainer(
          duration: const Duration(milliseconds: 200),
          margin: const EdgeInsets.only(left: 32.0, top: 4.0, bottom: 16.0),
          height: isActive ? 60.0 : 40.0,
          decoration: BoxDecoration(
            border: Border.all(
              color: isActive ? Colors.blue : Colors.grey.shade300,
              width: isActive ? 2.0 : 1.0,
            ),
            borderRadius: BorderRadius.circular(8.0),
            color: isActive ? Colors.blue.withOpacity(0.1) : Colors.grey.shade100,
          ),
          child: Center(
            child: Text(
              '拖放程序块到这里',
              style: TextStyle(
                color: isActive ? Colors.blue : Colors.grey,
                fontSize: 12.0,
                fontWeight: isActive ? FontWeight.bold : FontWeight.normal,
              ),
            ),
          ),
        );
      },
    );
  }
  
  // 显示块选项对话框
  void _showBlockOptionsDialog(ProgramBlock block) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text('编辑 ${block.name}'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 参数编辑
            if (block.parameters.isNotEmpty) ...[
              const Text('参数:'),
              const SizedBox(height: 8.0),
              ...block.parameters.map((param) {
                return Padding(
                  padding: const EdgeInsets.only(bottom: 8.0),
                  child: TextField(
                    decoration: InputDecoration(
                      labelText: param,
                      border: const OutlineInputBorder(),
                    ),
                    controller: TextEditingController(
                      text: block.parameterValues[param].toString(),
                    ),
                    keyboardType: TextInputType.number,
                    onChanged: (value) {
                      final numValue = double.tryParse(value);
                      if (numValue != null) {
                        setState(() {
                          block.parameterValues[param] = numValue;
                          widget.onProgramChanged(widget.program);
                        });
                      }
                    },
                  ),
                );
              }).toList(),
            ],
            
            // 控制类块的特殊选项
            if (block.type == BlockType.control) ...[
              const SizedBox(height: 16.0),
              const Text('控制选项:'),
              const SizedBox(height: 8.0),
              ElevatedButton.icon(
                icon: const Icon(Icons.add),
                label: const Text('添加子块'),
                onPressed: () {
                  Navigator.pop(context);
                  // 这里可以添加子块的逻辑
                },
              ),
            ],
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('关闭'),
          ),
        ],
      ),
    );
  }
  
  // 保存程序
  void _saveProgram() {
    final nameController = TextEditingController(text: widget.program.name);
    
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('保存程序'),
        content: TextField(
          controller: nameController,
          decoration: const InputDecoration(
            labelText: '程序名称',
            border: OutlineInputBorder(),
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () {
              setState(() {
                widget.program.name = nameController.text;
                // 这里可以添加实际保存到存储的逻辑
                ScaffoldMessenger.of(context).showSnackBar(
                  SnackBar(content: Text('程序 "${widget.program.name}" 已保存')),
                );
              });
              Navigator.pop(context);
            },
            child: const Text('保存'),
          ),
        ],
      ),
    );
  }
  
  // 加载程序
  void _loadProgram() {
    // 这里可以添加从存储加载程序的逻辑
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(content: Text('加载程序功能尚未实现')),
    );
  }
  
  // 清空程序
  void _clearProgram() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('清空程序'),
        content: const Text('确定要清空当前程序吗？此操作无法撤销。'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () {
              setState(() {
                widget.program.clear();
                widget.onProgramChanged(widget.program);
              });
              Navigator.pop(context);
            },
            child: const Text('清空'),
          ),
        ],
      ),
    );
  }
} 